package chixing.day20.work2;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class Manage {
    private Map<Integer, Product> products = new ConcurrentHashMap<>();
    private Map<Integer, FlashSale> flashSales = new ConcurrentHashMap<>();
    private Map<Integer, Order> orders = new ConcurrentHashMap<>();
    private AtomicInteger orderCounter = new AtomicInteger(1);

    // 添加商品
    public void addProduct(Product product) {
        products.put(product.getProductId(), product);
    }

    // 添加限时抢购活动
    public void addFlashSale(FlashSale flashSale) {
        flashSales.put(flashSale.getProductId(), flashSale);
    }

    // 用户下单
    public synchronized Order placeOrder(int productId, int quantity) {
        Product product = products.get(productId);
        if (product == null) {
            System.out.println("商品不存在");
            return null;
        }

        // 判断库存是否充足
        if (product.getProductStock() < quantity) {
            System.out.println("库存不足，无法下单");
            return null;
        }

        // 计算价格
        double finalPrice = product.getProductPrice() * quantity;
        FlashSale flashSale = flashSales.get(productId);

        // 若在限时活动期间，则按折扣计算价格
        if (flashSale != null && flashSale.isFlashSaleActive()) {
            finalPrice = product.getProductPrice() * flashSale.getDiscount() * quantity;
        }

        // 扣减库存
        product.setProductStock(product.getProductStock() - quantity);

        // 生成订单
        int orderId = orderCounter.getAndIncrement();
        Order order = new Order(orderId, productId, quantity, finalPrice);
        orders.put(orderId, order);

        // 输出订单信息
        System.out.println("用户下单成功：订单ID " + orderId +
                ", 商品: " + product.getProductName() +
                ", 数量: " + quantity +
                ", 支付金额: " + finalPrice);
        System.out.println("剩余库存: " + (int)product.getProductStock());

        return order;
    }

    // 获取商品信息
    public Product getProduct(int productId) {
        return products.get(productId);
    }

    // 获取订单信息
    public Order getOrder(int orderId) {
        return orders.get(orderId);
    }
}

